import type { FormInstance } from 'element-plus'
import type { SystemRoleOptionsType, SystemRoleDataItemType } from './typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  // ElSelect,
  // ElOption,
  ElButton,
  ElMessage,
  ElIcon
} from 'element-plus'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'
// import { UserRoleEnum } from '~/store/system/typings'
import { handleTrim } from '~/utils/util'
// import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '~/pages/system/index.module.scss'

export default defineComponent({
  name: 'SystemRoleOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemRoleOptionsType, { emit }) {
    const store = useStore()
    // const systemRoleState = useVuexGetters('systemRole', ['userRoleSelectList', 'userRoleEnum']) // 上级角色 // 暂隐藏
    const ruleFormRef = ref<FormInstance>()
    const title = { add: '新增', update: '编辑', read: '查看' }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    return () => {
      const { type, visible } = props
      const optionsValidateForm = reactive<SystemRoleDataItemType>(
        Object.assign(
          {
            roleName: '',
            roleAlias: '',
            leaderRole: '',
            parentId: '',
            sort: undefined
          },
          props.record
        )
      )

      // 提交表单
      const handleSubmitForm = () => {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validate(async (valid) => {
          if (!valid) return
          // 去输入的前后空格
          optionsValidateForm.roleName = handleTrim(optionsValidateForm.roleName ?? '')
          optionsValidateForm.roleAlias = handleTrim(optionsValidateForm.roleAlias ?? '')

          const params = { ...optionsValidateForm }
          const res = await store.dispatch('systemRole/PostUserRoleSubmit', params) // 角色的 新增与编辑 为同一接口
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })
            handleCloseModal()
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      }
      return (
        <ElDialog
          width={'30%'}
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <CirclePlus />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>
                    <ElIcon>
                      <CircleClose />
                    </ElIcon>
                    取消
                  </ElButton>
                </>
              )
            }
          }
        >
          <div class={styles['systemRoleOption-form']}>
            <ElForm label-width="100px" ref={ruleFormRef} model={optionsValidateForm}>
              <ElFormItem
                prop="roleName"
                label="角色名称"
                rules={[{ required: true, message: '请输入 角色名称', trigger: 'change' }]}
              >
                {type === 'read' ? (
                  optionsValidateForm.roleName
                ) : (
                  <ElInput
                    v-model={optionsValidateForm.roleName}
                    placeholder="请输入 角色名称"
                    clearable
                  />
                )}
              </ElFormItem>
              {/* <ElFormItem
                prop="roleAlias"
                label="角色别名"
                rules={[{ required: true, message: '请输入 角色别名', trigger: 'change' }]}
              >
                {type === 'read' ? (
                  optionsValidateForm.roleAlias
                ) : (
                  <ElInput
                    v-model={optionsValidateForm.roleAlias}
                    placeholder="请输入 角色别名"
                    clearable
                  />
                )}
              </ElFormItem> */}
              {/* <ElFormItem prop="parentId" label="上级角色"> // 暂隐藏
                {type === 'read'
                  ? (
                      systemRoleState.userRoleEnum.value?.[optionsValidateForm.parentId!] || '顶级'
                    )
                  : (
                  <ElSelect
                    v-model={optionsValidateForm.parentId}
                    placeholder="请选择 或输入关键字"
                    filterable
                    clearable
                  >
                    {systemRoleState.userRoleSelectList?.value?.map((item: UserRoleEnum) => (
                      <ElOption key={item?.id} label={item?.title} value={item?.id!} />
                    ))}
                  </ElSelect>
                    )}
              </ElFormItem> */}
              <ElFormItem
                prop="sort"
                label="角色排序"
                rules={[{ required: true, message: '请输入 角色排序', trigger: 'change' }]}
              >
                {type === 'read' ? (
                  optionsValidateForm.sort
                ) : (
                  <ElInputNumber
                    v-model={optionsValidateForm.sort}
                    min={0}
                    controls-position="right"
                    placeholder="请输入 角色排序"
                  />
                )}
              </ElFormItem>
            </ElForm>
          </div>
        </ElDialog>
      )
    }
  }
})
